import Cookies from 'js-cookie'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  editTemplates: {
    templates: [],
    chosenTemplates: []
  }
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  UPDATE_TEMPLATES: (state, templates) => {
    state.editTemplates.templates = templates
  },
  RESET_TEMPLATES: (state) => {
    state.editTemplates.chosenTemplates = []
  },
  APPEND_CHOSEN_TEMPLATE: (state, oid) => {
    state.editTemplates.chosenTemplates.push(oid)
  },
  CHANGE_CHOSEN: (state, args) => {
    const { oid, type } = args
    const index = state.editTemplates.chosenTemplates.findIndex((item) => { return item.oid === oid })
    if (type === 1) {
      if (index > 0) {
        const before = state.editTemplates.chosenTemplates[index - 1]
        const now = state.editTemplates.chosenTemplates[index]
        state.editTemplates.chosenTemplates.splice(index - 1, 2, now, before)
      }
    } else if (type === 2) {
      if (index < state.editTemplates.chosenTemplates.length - 1) {
        const next = state.editTemplates.chosenTemplates[index + 1]
        const now = state.editTemplates.chosenTemplates[index]
        state.editTemplates.chosenTemplates.splice(index, 2, next, now)
      }
    } else if (type === 3) {
      state.editTemplates.chosenTemplates.splice(index, 1)
    }
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  resetTemplates({ commit }) {
    commit('RESET_TEMPLATES')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setTemplates({ commit }, templates) {
    commit('UPDATE_TEMPLATES', templates)
  },
  appendTemplates({ commit }, id) {
    commit('APPEND_CHOSEN_TEMPLATE', id)
  },
  changeChosenTemplate({ commit }, args) {
    commit('CHANGE_CHOSEN', args)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
